# coding: utf-8
import web
import os,sys, string
import time
import datetime
import MySQLdb
import json

#db=MySQLdb.connect(host='127.0.0.1',user='kgetdata',passwd='kwoldb123456',db='get_history_data',port=3306)
db = web.database(dbn='mysql',host='127.0.0.1', user='root', pw='king+5688', db='k_cobbler',unix_socket="/var/lib/mysql/mysql.sock")
urls = (
    '/kis_cobbler_api_getdata', 'kis_cobbler_api_getdata',
    '/kis_cobbler_api_postresult','kis_cobbler_api_postresult',
)

class kis_cobbler_api_getdata:
	def POST(self):
		data = web.data()
		try:
			input = json.loads(data)
		except Exception, e:
			return e
		try:
			result = db.query("SELECT * FROM kis_cobbler_server where sn = '%s' and state_code = 0" % input['sn'])[0]
			result = "result|ok\teth0|%s\teth1|%s\thostname|%s\tpassword|%s\n" %(result['eth0'],result['eth1'],result['hostname'],result['password'])
			return result
		except Exception, e:
			return e

class kis_cobbler_api_postresult:
	def POST(self):
		data = web.data()
		try:
			input = json.loads(data)
			if input['result'] == "0":
				state_code = "`state_code` = 1"
			else:
				state_code = "`state_code` = 2"
			db.query("UPDATE `kis_cobbler_server` SET %s, `state` = 'configuration completed' , `message` = '%s' WHERE `sn` = '%s';" %(state_code,input['message'],input['sn']))
		except Exception, e:
			return e


#if __name__ == '__main__':
app = web.application(urls,globals())
application = app.wsgifunc()
#app.run()
